'use strict'

import axios from 'axios'
import router from '@/router'
import {Loading, MessageBox} from 'element-ui'
// axios.defaults.baseURL = 'http://39.106.139.151:8585/xbkj-dj/'  //39
axios.defaults.baseURL = '/xbkj-dj'   //李

let loadingInstance = ''
axios.interceptors.request.use(config => { // 这里的config包含每次请求的内容
  config.headers['content-type'] = 'application/json; charset=utf-8'
  config.headers.dataType = 'json'
  // 判断localStorage中是否存在api_token
  if (localStorage.getItem('ticket')) {
    //  存在将api_token写入 request header
    config.headers.token = localStorage.getItem('ticket')
  }
  loadingInstance = Loading.service({fullscreen: true})
  return config
}, err => {
  loadingInstance.close()
  return Promise.reject(err)
})

axios.interceptors.response.use(
  response => {
    loadingInstance.close()
    return response
  },
  error => {
    loadingInstance.close()
    if (error.response) {
      switch (error.response.status) {
        case 403:
          MessageBox.alert('登录失效，请重新登录', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              localStorage.removeItem('ticket')
              router.replace('/login')
            }
          })
      }
    }
    return Promise.reject(error.response.data) // 返回接口返回的错误信息
  }
)

// 请求方式的配置
export default {
  post (url, data) { // post
    return axios({
      method: 'post',
      url,
      data: JSON.stringify(data),
      timeout: 1000 * 10
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  get (url, params) { // get
    return axios({
      method: 'get',
      url,
      params, // get 请求时带的参数
      timeout: 1000 * 10
    }).then(response => {
      return response
    }).then(res => {
      return res
    })
  }
}
